package com.mvc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author wzm
 * @create 2023-04-07 14:14
 */
//定义打开和关闭数据库连接的方法
public class JDBCUtils {
   private static DataSource dataSource = null;

    //静态代码块 只要类加载代码块就会被执行
    static {
        try {
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得数据库连接
    public static Connection getConn(){
        try {
            //正常运行 返回连接
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //出现异常返回null
        return null;
    }


    //关闭数据库资源
    public static void closes(Connection connection, PreparedStatement statement, ResultSet rs){
      //后开先关
       try {
           if(rs != null){
               rs.close();
           }

        if(statement != null){
            statement.close();
        }

        if(connection != null){
                connection.close();
        }
       } catch (Exception e) {
           e.printStackTrace();
       }

    }
}
